﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml.Linq;

namespace SvnLightClient
{
    public class SvnLightClient : WebClient
    {
        public string WorkDirectory { get; set; }
        public string ServerUrl { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

        public event Action<string> GetProcessing;

        public void Get(string relativePath)
        {
            if (GetProcessing != null)
                GetProcessing(relativePath);

            if (ServerUrl.StartsWith("https") &&
                    ServicePointManager.ServerCertificateValidationCallback == null)
            {
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            }
            if (this.Credentials == null)
            {
                this.Credentials = new NetworkCredential(UserName, Password);
            }

            var absolutePath = ServerUrl + relativePath;
            
            if (relativePath.EndsWith("/"))
            {
                if (relativePath == "/")
                    throw new ArgumentException("can not get from svn root.");

                var info = this.DownloadString(absolutePath);
                var xdoc = XDocument.Parse(info);
                var index = xdoc.Descendants("index").First();
                if (index.Attribute("path").Value == "/")
                    Directory.CreateDirectory(Path.Combine(WorkDirectory, index.Attribute("base").Value));
                else
                    Directory.CreateDirectory(Path.Combine(WorkDirectory, index.Attribute("path").Value));
                foreach (var item in index.Descendants().Where(x => x.Name == "file" || x.Name == "dir"))
                {
                    Get(index.Attribute("path").Value + "/" + item.Attribute("href").Value);
                }
            }
            else
            {
                var fileName = relativePath.Substring(relativePath.IndexOf("/") + 1);
                fileName = Path.Combine(WorkDirectory, fileName);
                var dir = Path.GetDirectoryName(fileName);
                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                this.DownloadFile(absolutePath, fileName);
            }
        }

        public void GetFileList(List<string> paths)
        {
            paths.ForEach(Get);
        }
    }
}
